<?php

namespace App\Service\Collect;

use App\Models\Article;
use App\Service\BaiduNlp;
use App\Service\Curl;
use App\Service\ProxyIp;
use Illuminate\Support\Facades\Cache;
use QL\QueryList;
use sources\service\DataBase\Import;

class Sogou extends Base
{
    // 从搜狗采集
    //   采集接口用curl不成功，
    //     QueryList与GuzzleHttp也不成功
    //   只有file_get_contents执行成功

    // 初始化
    protected function init()
    {
        parent::init();
    }


    // 保存到数据表
    public function saveApiDataToDb($_item, $key, $is_file = false)
    {
        $_title  = $_item['title'];
        $_href   = $_item['href'];
        $_date   = $_item['time'];    // <script>document.write(timeConvert('1650499772'))</script>
        $_author = $_item['author'];
        $_cover  = $_item['cover'];
        $_desc   = $_item['desc'];
        $_ctime  = substr($_date, 36, 10); // 时间

        // 采集地址
        $domain = 'https://weixin.sogou.com/';
        $_href  = $this->realHref($_href, $domain);
        $_cover = $this->realHref($_cover);

        // 只采集有评论的
        /*if($_item['comment'] < 1){
            return $this->return_false(' '.($key + 1).'：==> 文章：评论数过少，不采集：'.$_title);
        }*/


        // 判断链接是否已经采集
        $articleDb = new Article();
        $info      = $articleDb->where('title', $_title)->first();
        //$info      = $this->isGather($_href);
        if($info){
            // 搜狗微信 如果已经采集 则更新链接
            $articleDb->where('id', $info->id)->update(['from_url' => $_href, 'verify' => 1]);

            return $this->return_false(' '.($key + 1).'：==>搜狗微信文章已经采集，更新链接 文章：'.$_title);
        }
        // 只采集今天的
        if($_ctime < $this->startTime){
            return $this->return_die(' '.($key + 1).'：==> 文章：不是今天的文章：'.$_title);
        }

        // 如果没有标题
        /*if(empty($_title)){
            return $this->return_false(' '.($key + 1).'：==> 文章：没有标题，不能采集：'.$_title);
        }*/

        // 全匹配 精准匹配
        if((strpos($_desc, $this->keyword) === false) && strpos($_title, $this->keyword) === false){
            return $this->return_false('==> 文章：文章没有精准匹配到搜索的关键字！');
        }
        // 排除关键字 宋正兴
        if(($this->keyword == '董事长宋正') && (strpos($_desc, '宋正兴') !== false) || strpos($_title, '宋正兴') !== false){
            return $this->return_false('==> 文章：文章匹配到其他关键词！');
        }


        // 判断 情感倾向
        //  "sentiment":2,   // 表示情感极性分类结果，0:负向，1:中性，2:正向
        /* $sentiment = '';  // 默认
        $full      = [0 => '负向', 1 => '中性', 2 => '正向'];
        $result    = (new BaiduNlp())->sentiment($_desc);
        if(isset($result['items'][0]['sentiment'])){
            $sentiment = $full[$result['items'][0]['sentiment']] ?? $sentiment;
        } */
        $sentiment = $this->baiduNlp($_desc);


        $_channel  = '';
        $from_site = '微信（搜狗）';
        $from_site = '微信公众号';
        $site_id   = 2;
        $_row      = [
            'channel'      => 'article',
            'sentiment'    => $sentiment,
            'link'         => $_href,
            'title'        => $_title,
            'description'  => $_desc,
            'text'         => $_desc,
            'time'         => $_ctime,
            'cover'        => $_cover,
            'author'       => trim($_author),
            'from_channel' => $_channel,
            'from_site'    => $from_site,
            'site_id'      => $site_id,
        ];

        //var_dump($_row);
        if($is_file){
            $res = $this->saveFile($_row);
        } else{
            $res = $this->saveArticle($_row);
        }

        return $res;
    }


    // 获取api接口的列表(测试)
    //   采集接口用curl需要 Cookie
    public function getApiList($keyword, $page = 1, $size = 10)
    {
        if(empty($keyword)){
            return $this->return_die('传递采集关键字！');
        }

        // 获取代理IP
        $proxy = (new ProxyIp())->getOneCheckDpsIp(time());

        // 执行 获取 HTML
        //  使用代理获取 html
        try{
            $url  = 'https://weixin.sogou.com/weixin?query='.$keyword.'&s_from=input&type=2&page='.$page.'&ie=utf8';
            $curl = new Curl();
            if($proxy){
                echo '使用代理进行采集'.chr(10);
                $html = $curl->url($url)->proxy($proxy)->request();
            } else{
                $html = $curl->url($url)->request();
            }
        } catch(\Exception $e){
            return $this->return_false($e->getMessage());
        }


        // 以前的获取数据
        /*$url   = 'https://weixin.sogou.com/weixin?query='.$keyword.'&s_from=input&type=2&page='.$page.'&ie=utf8';
        $lists = $this->getQLList($url, '#wrapper .news-box', '.news-list li', $rule);
        if(empty($lists)){
            return $this->return_die('没有采集内容');
        }*/

        $rule = [
            'href'   => ['.img-box a', 'href'],
            'cover'  => ['.img-box a img', 'src'],
            'title'  => ['.txt-box h3', 'text'],
            'desc'   => ['.txt-box .txt-info', 'text'],
            'author' => ['.txt-box .s-p span.all-time-y2', 'text'],
            'time'   => ['.txt-box .s-p span.s2', 'html'],
        ];

        // 使用代理的获取数据
        $encode = mb_detect_encoding($html, array("ASCII", "UTF-8", "GB2312", "GBK", "BIG5"), true);
        if($encode != 'UTF-8'){
            $html = mb_convert_encoding($html, "UTF-8", $encode); //编码转换为utf-8
        }

        // 组合整理数据
        $html  = QueryList::html($html)->find('#wrapper .news-box')->html();
        $ql    = QueryList::html($html);
        $lists = $ql->range('.news-list li')->rules($rule)->queryData();

        return $lists;
    }

    // 获取ip 作为代理使用
    protected function getIp()
    {
        // 账户API密钥
        $secretId  = "udsrhgug995rrjo1ppij";
        $secretKey = "yr00iclv1h5kkpfu96k8dhr3q1m9jvfc";
        // 订单API密钥
        $orderId   = "911169750935821";
        $secretId  = 'ob4tn5ryobn7iruaaahi';
        $secretKey = "yhsaez2egwwdxnk2d7d30fta5i2buf5v";


        $url = 'https://dps.kdlapi.com/api/getdps/?secret_id='.$secretId.'&signature=yhsaez2egwwdxnk2d7d30fta5i2buf5v&num=1&pt=1&format=text&sep=1&dedup=1&timestamp='.time().'&nonce='.rand(1000, 100000);
    }


}

